import React, { Component } from 'react';
import {
    Text,
    Image,
    View,
    TouchableOpacity,
    ScrollView,
    TextInput,
    ToastAndroid,
    DeviceEventEmitter
} from 'react-native';
import api from '../../../api'
import config from '../../../config';
import JPushModule from 'jpush-react-native'
import LoginCSS from '../../../css/login';
import { setToken } from '../../../utils/token'
import { setUsername,setPassword,setHeadImgUrl } from '../../../utils/user'
export default class Expert extends Component {
    constructor(props) {
        super(props);
        //两个状态用户输入框文本，密码框文本
        this.state = {
            registrationId:"",
            alias: '',
            form: {
                username: '',
                password: ''
            }
        }
        //获取registrationId
        JPushModule.getRegistrationID(registrationId => {     
          
          this.setState({
            registrationId: registrationId
          })
        })
      
    }
    //获取别名
//    getAlias = () => {
//     JPushModule.getAlias(map => {
//         console.warn(map.errorCode);
//         console.warn( map.alias);
//       if (map.errorCode === 0) {
//           this.setState({
//             alias:map.alias,
//           })
//         console.log('Get alias succeed, alias: ' + map.alias)
//       } else {
//         console.log('Get alias failed, errorCode: ' + map.errorCode)
//       }
//     })
//   }
setAlias () {
    if (this.state.alias !== undefined) {
      JPushModule.setAlias(this.state.alias, map => {
        if (map.errorCode === 0) {
          console.log('set alias succeed')
        } else {
          console.log('set alias failed, errorCode: ' + map.errorCode)
        }
      })
    }
  }
    //点击事件函数
    login() {   
       
        api.user.login(this.state.form).then(response => {
            if(response.code == 401){
                ToastAndroid.show(response.message, ToastAndroid.SHORT);
            }else{
            localStorage.token = response.token;
          //  console.warn(localStorage.token)
            setToken(response.token)
            api.user.user({'login-token':response.token}).then(response => {
                setUsername(response.username);
                setPassword(response.password);
               
                localStorage.name = response.username;
                
                localStorage.pass = response.password;
                localStorage.id = response.id;
             
                localStorage.nickname = response.nickname; 
          
                localStorage.type = response.type;
               // localStorage.typestatus = data.typestatus;
                localStorage.userstatus=1;
                // JPushModule.getInfo(map => {
                //      this.setState({
                //       deviceId: map.myDeviceId,
                //      })
                //   })
               
                JPushModule.setAlias(String(localStorage.id), map => {
                  
                    if (map.errorCode === 0) {
                     
                  
               
                if(localStorage.type == 1){
                   
                 //牧民个人信息
                 api.user.mumin({'login-token':localStorage.token,'id':localStorage.id}).then(response => {
                       //  console.warn(response)
                         if(response.id != null && response.province != null && response.city != null && response.area != null){
                         localStorage.wanshan=2;
                         setHeadImgUrl({uri:config.img_url+response.headerUrl});
                         localStorage.headImgUrl ={uri:config.img_url+response.headerUrl};
                         DeviceEventEmitter.emit('headImgUrl', localStorage.headImgUrl)
                         }else{
                         localStorage.wanshan=1;
                         }
                         JPushModule.getAlias(map => {
                            
                            this.setState({
                                alias:map.alias,
                              })
                             
                              api.user.deviceId({'login-token':localStorage.token,'id':localStorage.id,'regsId':this.state.alias}).then(response => {
                                ToastAndroid.show('登录成功', ToastAndroid.SHORT)
                                this.props.navigation.goBack(null)
                             })
                        })
                       
                        
                     })
                     //专家个人信息
                    }else if(localStorage.type == 2){
                       
                        api.user.zhuanjia({'login-token':localStorage.token}).then(response => {
                            console.warn(response)
                           
                            
                            if(response.id != null){
                            localStorage.wanshan=2;
                            setHeadImgUrl({uri:config.img_url+response.headerUrl});
                            localStorage.headImgUrl ={uri:config.img_url+response.headerUrl};
                            DeviceEventEmitter.emit('headImgUrl', localStorage.headImgUrl)
                            }else{
                            localStorage.wanshan=1;
                            }
                            JPushModule.getAlias(map => {
                               
                                this.setState({
                                    alias:map.alias,
                                  })
                             
                                  api.user.deviceId({'login-token':localStorage.token,'id':localStorage.id,'regsId':this.state.alias}).then(response => {
                                    ToastAndroid.show('登录成功', ToastAndroid.SHORT)
                                    this.props.navigation.goBack(null)
                                 })
                            })
                           
                        })

                    }else if(localStorage.type == 3){
                        
                        api.user.yaodian({'login-token':localStorage.token}).then(response => {
                           // console.warn(response)
                          
                            if(response.id != null && response.province != null && response.city != null && response.area != null){
                            localStorage.wanshan=2;
                            setHeadImgUrl({uri:config.img_url+response.headerUrl});
                            localStorage.headImgUrl ={uri:config.img_url+response.headerUrl};
                            DeviceEventEmitter.emit('headImgUrl', localStorage.headImgUrl)
                            }else{
                            localStorage.wanshan=1;
                            }
                           // this.getAlias();
                           JPushModule.getAlias(map => {
                               
                            this.setState({
                                alias:map.alias,
                              })
                              api.user.deviceId({'login-token':localStorage.token,'id':localStorage.id,'regsId':this.state.alias}).then(response => {
                                ToastAndroid.show('登录成功', ToastAndroid.SHORT)
                                this.props.navigation.goBack(null)
                             })
                        })
                           
                        })
                    }
                     //ToastAndroid.show('登陆成功！', ToastAndroid.SHORT);
                     //this.props.navigation.goBack(null) 
                    } else {
                        console.warn('set alias failed, errorCode: ' + map.errorCode)
                      }
                    })
                 
            })
      
           }
        })
       
    }
    //设置手机号
    setPhone(phone) {
        let form = this.state.form
        form.username = phone
        this.setState({
            form: form
        })
    }
    //设置密码
    setPassword(password) {
        let form = this.state.form
        form.password = password
        this.setState({
            form: form
        })
    }
    // 此处设置 Tab 的名称和一些样式，这里的会覆盖掉配置路由文件的样式，下面会讲
    static navigationOptions = {
    };
    _onPressButton() {
        console.log("You tapped the button!");
    }
    componentDidMount() {

        // DeviceEventEmitter.addListener('register', (message) => {
        //    // console.warn(message)
        //    // this.getMessage(message); 
        //    this.setState({
        //        form:{
        //            username:message.username,
        //            pass:message.pass
        //        }
        //    })  
        // })
    }
    render() {
        const { navigate } = this.props.navigation;
        return (
            <ScrollView style={[LoginCSS.mainStyle]}>
                <View style={[LoginCSS.container]}>
                    <View style={[LoginCSS.header]}>
                        <TouchableOpacity style={[LoginCSS.backImg]} onPress={() => { this.props.navigation.goBack(null) }}>
                            <Image source={require('../../../img/nav_back01.png')} />
                        </TouchableOpacity>
                        <View style={LoginCSS.title}>
                            <Text style={[LoginCSS.titleText]}>登录</Text>
                        </View>         
                    </View>
                    <View>
                        <View style={[LoginCSS.loginInformation]}>
                            <Text style={[LoginCSS.loginText]}>账号</Text>
                            <TextInput placeholder="请输入手机号"
                                underlineColorAndroid='transparent'
                                style={[LoginCSS.LoginInput]}
                                onChangeText={(username) => this.setPhone(username)}
                            ></TextInput>
                        </View>
                        <View style={[LoginCSS.loginInformation]}>
                            <Text style={[LoginCSS.loginText]}>密码</Text>
                            <TextInput placeholder="请输入密码"
                                secureTextEntry={true}
                                underlineColorAndroid='transparent'
                                style={[LoginCSS.LoginInput]}
                                onChangeText={(password) => this.setPassword(password)}>
                                </TextInput>
                        </View>
                        <View style={[LoginCSS.handles]}>
                            <TouchableOpacity style={[LoginCSS.loginbtn]} 
                            //点击事件，要记得绑定
                            onPress={() => this.login()}>
                                <Text style={[LoginCSS.loginbtnText]}>登录</Text>
                            </TouchableOpacity>
                            <View style={[LoginCSS.handle]}>
                            <TouchableOpacity style={[LoginCSS.register]} onPress={() => navigate('Register')}>
                                    <Text style={[LoginCSS.registerText]}>注册账号</Text>
                                </TouchableOpacity>
                                <View>
                                    <Text style={[LoginCSS.uprightText]}> | </Text>
                                </View>
                                <TouchableOpacity style={[LoginCSS.forgotpassword]} onPress={() => navigate('ForgetPassword')}>
                                    <Text style={[LoginCSS.forgotpasswordText]}>忘记密码</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                </View>
            </ScrollView>
        );
    }

}